// pages/mine/mine.js
const app = getApp ();
Page ({
  /**
     * 页面的初始数据
     */
  data: {
    userInfo: {},
    hasUserInfo: false,
    avatarUrl: '',
    nickName: '',
    openId: '',
    uid: '',
  },

  /**
     * 生命周期函数--监听页面加载
     */
  onLoad: function (options) {
    this.setData ({
      avatarUrl: wx.getStorageSync ('avatarUrl'),
      nickName: wx.getStorageSync ('nickName'),
      uid: wx.getStorageSync ('uid'),
    });

    if (app.globalData.userInfo) {
      this.setData ({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
      });
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData ({
          userInfo: res.userInfo,
          hasUserInfo: true,
        });
      };
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo ({
        success: res => {
          app.globalData.userInfo = res.userInfo;
          this.setData ({
            userInfo: res.userInfo,
            hasUserInfo: true,
          });
        },
      });
    }
    wx.setNavigationBarTitle ({
      title: '我的',
    });
    if (wx.getStorageSync ('token') === '') {
      this.setData ({
        showLoginButton: true,
      });
    } else {
      this.setData ({
        showLoginButton: false,
      });
    }
  },

  /**
     * 预览图片
     */

  previewImage: function (event) {
    let url = event.target.id;
    let baseUrl = this.headimgHD (url);
    wx.previewImage ({
      current: '',
      urls: [baseUrl],
    });
  },

  /**
     * 将微信头像URL返回为高清
     * @param {*} imageUrl
     */
  headimgHD: function (imageUrl) {
    imageUrl = imageUrl.split ('/'); //把头像的路径切成数组
    //把大小数值为 46 || 64 || 96 || 132 的转换为0
    if (
      imageUrl[imageUrl.length - 1] &&
      (imageUrl[imageUrl.length - 1] == 46 ||
        imageUrl[imageUrl.length - 1] == 64 ||
        imageUrl[imageUrl.length - 1] == 96 ||
        imageUrl[imageUrl.length - 1] == 132)
    ) {
      imageUrl[imageUrl.length - 1] = 0;
    }
    imageUrl = imageUrl.join ('/'); //重新拼接为字符串
    return imageUrl;
  },

  /**
     * 授权登录
     * @param e
     */
  getAuthUserInfo: function (e) {
    let that = this;
    wx.getUserProfile ({
      desc: '正在授权信息',
      success: function (e) {
        that.setData ({
          avatarUrl: e.userInfo.avatarUrl,
          nickName: e.userInfo.nickName,
          userInfo: e.userInfo.userInfo,
          hasUserInfo: true,
        });
        wx.login ({
          success: res => {
            console.log('code',res.code)
            wx.request ({
              url: app.globalData.baseUrl + '/sys/getWxOpenId',
              method: 'GET',
              data: {
                code: res.code,
              },
              success: res => {
                if (res.data.code === 200) {
                  wx.setStorageSync ('openId', res.data.result);
                  wx.request ({
                    url: app.globalData.baseUrl + '/sys/wxAuthLoginOrRegister',
                    method: 'POST',
                    data: {
                      nickName: that.data.nickName,
                      avatar: that.data.avatarUrl,
                      wxOpenId: wx.getStorageSync ('openId'),
                    },
                    header: {
                      'Content-Type': 'application/json;charset=utf-8',
                    },
                    success: res => {
                      if (res.data.code === 200) {
                        wx.setStorageSync ('token', res.data.result);
                        wx.setStorageSync ('avatarUrl', that.data.avatarUrl);
                        wx.setStorageSync ('nickName', that.data.nickName);
                        wx.showToast ({
                          title: '授权登录成功',
                          icon: 'none',
                        });
                        that.setData ({
                          showLoginButton: false,
                        });
                      } else {
                        wx.showToast ({
                          title: '授权登录失败',
                          icon: 'none',
                        });
                      }
                    },
                  });
                } else {
                  wx.showToast ({
                    title: '授权登录失败',
                    icon: 'none',
                  });
                }
              },
              fail: function () {
                wx.showToast ({
                  title: '授权登录失败',
                  icon: 'none',
                });
              },
            });
          },
        });
      },
      fail: function (err) {
        console.log ('获取失败: ', err);
      },
    });
  },
});
